<template>
    <div style="height:100%">
      <!-- 查看表格信息 + 按钮 -->
      <div v-show="BusVisible">
        <div class='content-title'>
          <div class='content-title-parent'>电商管理</div>
          /
          <div class='content-title-child' @click="setBusVisible">商家管理</div>
        </div>
        <hr class='content-hr'/>
        <!-- 筛选+按钮 -->
        <el-row class='businessClass'>
          <el-form v-model="filterForm" ref="filterForm":inline="true" >
            <el-form-item label="所属机场：">
              <el-cascader
                clearable
                v-model="filterForm.airportList"
                expand-trigger="hover"
                :options="filterForm.airportNameList"
                @change="selectAirport('filterForm')"
                :props="airportProps"
                >
              </el-cascader>
            </el-form-item>
            <el-form-item label="商家名称：" style="margin-left:10px">
              <el-input v-model.trim="filterForm.placeName" @keyup.native="filterForm.placeName=filterForm.placeName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable placeholder="请选择">
              </el-input>
            </el-form-item>
            <el-button type="info" style="background-color:#2280E9;border-color:#2280E9" @click="submitSearch()">查询</el-button>
            <el-button type="warning" style="float:right;margin-right:10px" @click="addBusinessVisible()">增加商家</el-button>
            <el-upload
              class="upload-demo"
              ref="uploadExc"
              style="float:right;margin-right:10px"
              action=""
              :limit = "1"
              :http-request="uploadBusinessFro"
              :on-preview="handlePreview"
              :on-progress="onProgress"
              :on-error="onErrorFile"
              :on-success="onSuccessFile"
              :before-upload = "beforeUploadExc"
              list-type="picture"
              accept="excel"
              :show-file-list="false">
              <el-button type="primary">批量导入</el-button>
            </el-upload>
          </el-form>
        </el-row>
        <!-- 表格数据 -->
        <el-row style="margin-top:5px" >
          <el-table
            v-loading="loading"
            :element-loading-text="loadingText"
            element-loading-spinner="el-icon-loading"
            :data="filterFormFro.tableData" 
            :border="true"
            :row-class-name="tableRowClassName"
            :header-cell-class-name = "tableHeaderClassName"
            v-bind:style="{width: tableWidth + 'px'}"
            ref="elTable"
            id="el-table">
              <el-table-column prop="index" label="序号"  min-width=5%>
              </el-table-column>
              <el-table-column prop="placeName" label="商家名称"  min-width=20%>
              </el-table-column>
              <el-table-column prop="airportName" label="所属机场" min-width=15%>
              </el-table-column>
              <el-table-column prop="businessAddress" label="商家地址" min-width=25%>
              </el-table-column>
              <el-table-column prop="location" label="坐标" min-width=20%>
              </el-table-column>
              <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <!-- 分页 -->
        <el-row>
          <div class="pagination" style="text-align:center" v-show="paginationVisible">
              <el-pagination
                @current-change="handleCurrentChange"
                background
                :current-page="filterForm.currentPage"
                :page-size="15"
                layout="total, prev, pager, next"
                :page-count="filterFormFro.totalPage">
              </el-pagination>
          </div>
        </el-row>
      </div>
      <!--增加商家信息-->
      <div v-show="addBusVisible">
        <div class='content-title'>
          <div class='content-title-parent'>电商管理</div>
          /
          <div class='content-title-parent'  @click="setBusVisible">商家管理</div>
          /
          <div class='content-title-child'>添加商家</div>
        </div>
        <hr class='content-hr'/>
        <div class='top-icon'>
          <div class='base-info' v-bind:class="{busLabel: busLabel}" @click="setBusLabelVisible(1)">
            <img :src="addBaseSrc"></img>
            <!-- <img src="../../../static/img/business-yes.png"></img> -->
            <br/>
            基本资料
          </div>
          <hr class='business-hr' style="margin-right:20px"></hr>
          <div class='base-info' v-bind:class="{busLabel: !busLabel}" @click="setBusLabelVisible(2)">
            <img :src="addLabelSrc"></img>
            <br/>
            标签设置
          </div>
        </div>
        <el-row style="margin-top:30px">
          <div class='addBus' v-show="!addBusLabelVisible">
            <div class='addBus-div' v-bind:style="{marginLeft: addBusWidth + 'px'}">
              <el-form :model="addForm" :rules="addRules" ref="addForm"  label-width="148px">
                <!-- <el-form-item>
                  <el-button type="primary" style="float:right" @click="submitAddBus()">保存</el-button>
                </el-form-item> -->
                <el-form-item label="所属机场：" prop="airportList" style="margin-top:10px">
                  <el-cascader
                    clearable
                    style="width:240px"
                    v-model="addForm.airportList"
                    expand-trigger="hover"
                    :options="addForm.airportNameList"
                    @change="selectAirport('addForm')"
                    :props="airportProps"
                  >
                  </el-cascader>
                </el-form-item>
                <hr style="border:none;border-bottom:2px dashed #dad9d7;width:800px;margin-top:15px"></hr>
                <el-form-item label="商家名称：" prop="placeName" style="margin-top:13px">
                  <el-input style="width:240px" @keyup.native="addForm.placeName=addForm.placeName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" placeholder="请输入商家名称" v-model.trim="addForm.placeName" ></el-input>
                </el-form-item>
                <el-form-item label="商家地址描述："  style="margin-top:13px" prop="address">
                  <el-input style="width:240px" @keyup.native="addForm.address=addForm.address.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" placeholder="请输入商家地址" v-model.trim="addForm.address" ></el-input>
                </el-form-item>
                <el-form-item label="商家图片：" prop="image" style="margin-top:13px">
                  <el-upload
                    style="width:500px"
                    ref="uploadImg"
                    class="el-upload-img"
                    action=""
                    :limit="1"
                    :http-request="addBusinessFro"
                    :on-preview="handlePreview"
                    :on-remove="addhandleRemove"
                    :on-change="addhandleChange"
                    :on-progress="onProgress"
                    :on-error="onError"
                    :on-success="onSuccess"
                    :before-upload = "beforeUploadImg"
                    list-type="picture"
                    :auto-upload="false"
                    :file-list="fileList">
                    <el-button v-show="addImgVisible" style="border:1px dashed #dad9d7;font-size:14px;color:#999999;height:40px">LOGO</el-button>
                    <div v-show="addImgVisible" slot="tip" class="el-upload__tip">图片尺寸不能超过50kb</div>
                  </el-upload>
                  <!-- <el-button @click="uploadImg()">点击上传</el-button> -->
                </el-form-item>
                <div style="clear:both"></div>
                <el-form-item label="商家地址：" style="margin-top:5px">
                  <div></div>
                  <div v-show="svgSelect.addpointVisible">
                    <span style="display:inline">{{addForm.pointAddress}}</span>
                    <img src='../../../static/img/close-point.png' class='close-point' @click="closeAddPoint()"></img>
                  </div>
                  <label style="fon-size:14px;color:#999999">使用鼠标右键或地图右上角“标记”按钮直接在地图上进行标记</label>
                  <!--标记点击，@click为点击事件，@mousedown为鼠标事件（获取当前的鼠标位置）-->
                  <div class='svgAdd' style="position:relative;width:500px;overflow:hidden;height:500px;float:left;border:2px solid #e8e9e9" v-bind:class="{'cursorClass': svgSelect.isCursor}">
                    <div id="svgmap" style="">
                    </div>
                    <!--左下角楼层选择-->
                    <div class="floor-list">
                        <ul class="list-bar">
                          <li v-for="(item,index) in svgSelect.floorList" :key="index" @click="selectFloor(item, index, 'addForm')"  v-bind:class="{ 'liSelectClass': item.active}">
                                {{item.select}}
                          </li>
                        </ul>
                    </div>
                    <!--右上角标记-->
                    <div class="floor-list-add">
                      <el-tooltip class="item" effect="dark" content="左键点击选择商家，右键取消" placement="top-start">
                        <img src='../../../static/img/图钉.png' @click="markClickButton()" @mousedown="getXY"/>
                        <!-- <img src='../../../static/img/add_location.png' @click="markClickButton()" @mousedown="getXY"/> -->
                      </el-tooltip>
                    </div>
                    <div class="floor-list-size">
                        <ul class="list-bar list-bar2 list-bar-size">
                            <li style="margin-top:5px" @click="changeViewBoxSize(1)">+</li>
                            <li style="margin-top:-10px" @click="changeViewBoxSize(-1)">-</li>
                        </ul>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
            <div style='text-align:center;clear:both;margin-top:20px' class='submit-button'>
              <el-button type="primary" style="width:240px;padding:10px 0px" @click="submitAddBus()">保 存</el-button>
            </div>
          </div>
          <div class='addBusLabel' v-show="addBusLabelVisible">
            <div class='addBusLabel-div' v-bind:style="{marginLeft: addBusLabelWidth + 'px'}">
              <el-form label-width="100px">
                  <el-form-item  v-for="(item,i) in this.addForm.categoryLabelList" :key="i" :label="item.category + '：'">
                    <el-button  v-for="(data,index) in item.label" :key='index' @click="changeLabel(i,index,item,'addForm')" :ref='"label-button" + i + index' :icon="data.icon" :type="data.type">{{data.value}}</el-button>
                  </el-form-item>
                  <!--<el-form-item >
                  <el-button type="info" style="float:right" @click="submitEditBus()">保存</el-button>
                  </el-form-item> -->
              </el-form>
            </div>
            <div style='text-align:center;clear:both;margin-top:20px' class='submit-button'>
              <el-button type="primary"  style="width:240px;border-radius:4px;padding: 6px 16px" @click="submitAddBus()">保 存</el-button>
            </div>
          </div>
        </el-row>
      </div>
      <!--编辑商家信息-->
      <div v-show="editBusVisible">
        <div class='content-title'>
          <div class='content-title-parent'>电商管理</div>
          /
          <div class='content-title-parent'  @click="setBusVisible">商家管理</div>
          /
          <div class='content-title-child'>编辑商家</div>
        </div>
        <hr class='content-hr'/>
        <div class='top-icon'>
          <div class='base-info' v-bind:class="{busLabel: busLabel}" @click="setEditBusLabelVisible(1)">
            <img :src="addBaseSrc"></img>
            <br/>
            基本资料
          </div>
          <hr class='business-hr' style="margin-right:20px"></hr>
          <div class='base-info' v-bind:class="{busLabel: !busLabel}" @click="setEditBusLabelVisible(2)">
            <img :src="addLabelSrc"></img>
            <br/>
            标签设置
          </div>
        </div>
        <el-row style="margin-top:30px">
          <div class='addBus' v-show="!editBusLabelVisible">
            <div class='addBus-div' v-bind:style="{marginLeft: addBusWidth + 'px'}">
              <el-form :model="editForm" :rules="editRules" ref="editForm"  label-width="148px">
                <!-- <el-form-item>
                  <el-button type="primary" style="float:right" @click="submitAddBus()">保存</el-button>
                </el-form-item> -->
                <el-form-item label="所属机场：" prop="airportList" style="margin-top:10px">
                  <el-cascader
                    clearable
                    style="width:240px"
                    v-model="editForm.airportList"
                    expand-trigger="hover"
                    :options="editForm.airportNameList"
                    @change="selectAirport('editForm')"
                    :props="airportProps"
                  >
                  </el-cascader>
                </el-form-item>
                <hr style="border:none;border-bottom:2px dashed #dad9d7;width:800px;;margin-top:15px"></hr>
                <el-form-item label="商家名称：" prop="placeName" style="margin-top:13px">
                  <el-input style="width:240px" @keyup.native="editForm.placeName=editForm.placeName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')"  placeholder="请输入商家名称" v-model.trim="editForm.placeName" ></el-input>
                </el-form-item>
                <el-form-item label="商家地址描述："  style="margin-top:13px" prop="address">
                  <el-input style="width:240px" @keyup.native="editForm.address=editForm.address.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" placeholder="请输入商家地址" v-model.trim="editForm.address" ></el-input>
                </el-form-item>
                <el-form-item label="商家图片：" prop="image" style="margin-top:13px">
                  <!-- <el-upload
                    style="width:500px"
                    ref="uploadImg"
                    class="el-upload-img"
                    action=""
                    :limit="1"
                    :http-request="addBusinessFro"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :on-change="handleChange"
                    :on-progress="onProgress"
                    :on-error="onError"
                    :on-success="onSuccess"
                    :before-upload = "beforeUploadImg"
                    list-type="picture"
                    :auto-upload="false"
                    :file-list="fileList"> -->
                    <el-upload
                    style="width:500px"
                    v-if="uploadEditImgShow"
                    ref="uploadEditImg"
                    class="el-upload-img"
                    action=""
                    :limit="1"
                    :http-request="editBusinessFro"
                    :on-preview="handlePreview"
                    :on-remove="edithandleRemove"
                    :on-change="edithandleChange"
                    :on-progress="onProgress"
                    :on-error="onError"
                    :on-success="onSuccess"
                    :before-upload = "beforeUploadImg"
                    list-type="picture"
                    :auto-upload="false"
                    :file-list="editForm.fileListEdit">
                    <el-button v-show="editImgVisible" style="border:1px dashed #dad9d7;font-size:14px;color:#999999;height:40px">LOGO</el-button>
                    <div v-show="editImgVisible" slot="tip" class="el-upload__tip">图片尺寸不能超过50kb</div>
                  </el-upload>
                  <!-- <el-button @click="uploadImg()">点击上传</el-button> -->
                </el-form-item>
                <div style="clear:both"></div>
                <el-form-item label="商家地址：" style="margin-top:5px">
                  <div></div>
                  <div v-show="svgSelect.editpointVisible">
                    <span style="display:inline">{{editForm.pointAddress}}</span>
                    <img src='../../../static/img/close-point.png' class='close-point' @click="closeEditPoint()"></img>
                  </div>
                  <label style="fon-size:14px;color:#999999">使用鼠标右键或地图右上角“标记”按钮直接在地图上进行标记</label>
                  <!--标记点击，@click为点击事件，@mousedown为鼠标事件（获取当前的鼠标位置）-->
                  <div class='svgEdit' style="overflow:hidden;position:relative;width:500px;height:500px;float:left;border:2px solid #e8e9e9" v-bind:class="{'cursorClass': svgSelect.isCursor}">
                    <div id="svgmap" style="">
                    </div>
                    <!--左下角楼层选择-->
                    <div class="floor-list">
                        <ul class="list-bar">
                          <li v-for="(item,index) in svgSelect.floorList" :key="index" @click="selectFloor(item, index, 'editForm')"  v-bind:class="{ 'liSelectClass': item.active}">
                                {{item.select}}
                          </li>
                        </ul>
                    </div>
                    <!--右上角标记-->
                    <div class="floor-list-add">
                      <el-tooltip class="item" effect="dark" content="左键点击选择商家，右键取消" placement="top-start">
                        <img src='../../../static/img/图钉.png' @click="markClickButton()" @mousedown="getXY"/>
                        <!-- <img src='../../../static/img/add_location.png' @click="markClickButton()" @mousedown="getXY"/> -->
                      </el-tooltip>
                    </div>
                    <div class="floor-list-size">
                        <ul class="list-bar list-bar2 list-bar-size">
                            <li style="margin-top:5px" @click="changeViewBoxSize(1)">+</li>
                            <li style="margin-top:-10px" @click="changeViewBoxSize(-1)">-</li>
                        </ul>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
            <div style='text-align:center;clear:both;margin-top:20px' class='submit-button'>
              <el-button type="primary" style="width:240px;padding:10px 0px" @click="submitEditBus()">保 存</el-button>
            </div>
          </div>
          <div class='addBusLabel' v-show="editBusLabelVisible">
            <div class='addBusLabel-div' v-bind:style="{marginLeft: addBusLabelWidth + 'px'}">
              <el-form label-width="100px">
                  <el-form-item  v-for="(item,i) in this.editForm.categoryLabelList" :key="i" :label="item.category + '：'">
                    <el-button  v-for="(data,index) in item.label" :key="index" @click="changeLabel(i,index,item,'editForm')" :ref='"label-button" + i + index' :icon="data.icon" :type="data.type">{{data.value}}</el-button>
                  </el-form-item>
              </el-form>
            </div>
            <div style='text-align:center;clear:both;margin-top:20px' class='submit-button'>
              <el-button type="primary" style="width:240px;border-radius:5px" @click="submitEditBus()">保 存</el-button>
            </div>
          </div>
        </el-row>
      </div>
    </div>
</template>
<style>
  .icon {
   width: 1em; height: 1em;
   vertical-align: -0.15em;
   fill: currentColor;
   overflow: hidden;
  }
</style>
<script>
import '../../../static/css/businessPlat/business.css'
import '../../../static/css/businessPlat/common.css'
import '../../../static/js/iconfont.js'
import * as d3 from 'd3'
import apiFile from '../../api/apiFile/apiFile.js'
import apiBus from '../../api/businessPlat/apiBus.js'
// 禁用浏览器右击事件
document.oncontextmenu = function (e) {
  e.preventDefault()
}
export default {
  created () {
    this.getAllBusLabelFro() // 查询所有标签
    this.getAllTerminalFro() // 查询所有航站楼和机场
    this.getBusinessListFro() // 查询筛选商家
    // this.getBusinessListFro()
  },
  data () {
    return {
      options: {
        text: '测试加载',
        target: document.getElementById('el-table')
      },
      addBusWidth: '', // 增加商家和偏移宽度
      addBusLabelWidth: '', // 增加商家标签偏移宽度
      tableWidth: '', // 表格宽度
      loadingText: '正在拼命加载中,请稍等......',
      busLabel: true, // 增加商家信息还是选择标签
      addBusVisible: false, // 增加商家是否可见
      BusVisible: true, // 查看商家表格数据是否可见
      addBusLabelVisible: false, // 增加商家-选择标签是否可见
      editBusVisible: false, // 编辑商家是否可见
      editBusLabelVisible: false, // 增加商家-选择标签是否可见
      paginationVisible: false, // 分页是否显示
      addImgVisible: true, // 上传图片按钮
      editImgVisible: true, // 编辑上传图片按钮
      uploadEditImgShow: true,
      addBaseSrc: './static/img/business-yes.png', // 增加商家基本信息图片链接
      addLabelSrc: './static/img/label-no.png', // 增加商家标签图片链接
      loading2: false, // 加载
      loading: false, // 页面加载
      Note: '', // 提交提示
      pointVisible: false, // 加载弹窗是否显示
      svg: function () { // 地图svg对象
        let svgDiv = d3.select(this.$el).selectAll('#svgmap')
        let svg = svgDiv.selectAll('svg')
        return svg
      },
      svgAdd: function () { // 地图svg对象
        let svgDiv = d3.select(this.$el).select('.svgAdd').select('#svgmap')
        let svg = svgDiv.select('svg')
        return svg
      },
      svgEdit: function () { // 地图svg对象
        let svgDiv = d3.select(this.$el).select('.svgEdit').select('#svgmap')
        let svg = svgDiv.select('svg')
        return svg
      },
      viewBox: function () { // svg中的viewBox属性
        // let svgDiv = d3.select(this.$el).select('#svgmap')
        // let svg = svgDiv.select('svg')
        let viewBox = this.svg().attr('viewBox').split(' ')
        for (let i = 0; i < viewBox.length; i++) {
          viewBox[i] = parseInt(viewBox[i])
        }
        return viewBox
      },
      svgSelect: {
        addpointVisible: false, // 增加商家地图上方坐标位置是否可见
        editpointVisible: true, // 编辑商家地图上方坐标位置是否可见
        center: [], // 选到的中心坐标
        centerXList: [], // 中心X坐标数组
        centerYList: [], // 中心Y坐标数组
        isCursor: false, // 是否选择右上角标记
        svgStr: '',
        floorList: [
          {select: 'F1'},
          {select: 'F2'},
          {select: 'F3'}
        ] // 机场楼层数目列表
      },
      markClick: false, // 地图右上角标记点
      clientX: 0, // 存储x的坐标
      clientY: 0, // 存储y的坐标
      fileList: [],
      addVisible: false,
      editVisible: false,
      filterFormFro: {
        tableData: [],
        totalPage: 0,
        allBusinessList: [] // 全部商家列表
      },
      filterForm: {
        airportNameList: [{ // 飞机及航站选择列表
          label: '安庆山天柱山机场',
          airportId: '0',
          terminals: [{
            label: '全部',
            terminalId: '00'
          }, {
            label: 'T2航站楼',
            terminalId: '01'
          }, {
            label: 'T1航站楼',
            terminalId: '02'
          }]
        }],
        currentPage: 1, // 当前页数
        airportId: '', // 机场ID
        terminalId: [], // 航站楼ID
        terminalName: [],
        airportName: '', // 机场名称
        airportList: [],
        placeName: '' // 商家名称
      },
      airportProps: {
        value: 'label',
        children: 'terminals'
      },
      formLabelWidth: '30%',
      addForm: {
        pointAddress: '',
        airportNameList: [],
        categoryLabelList: [],
        airportList: [],
        airportId: '', // 机场ID
        airportName: '', // 机场名称
        placeName: '', // 商家名称
        latitude: '',
        longitude: '',
        address: '',
        floor: 1,
        labelIds: [],
        labelList: [],
        terminalId: [],
        terminalName: []
      },
      editForm: {
        isImage: 0,
        airportNameList: [],
        pointAddress: '',
        index: 0, // 所在表格index
        categoryLabelList: [],
        airportList: [],
        fileListEdit: [{url: ''}], // 编辑商家的图片链接list
        airportId: '', // 机场ID
        airportName: '', // 机场名称
        placeName: '', // 商家名称
        latitude: '',
        longitude: '',
        address: '',
        floor: 1,
        labelIds: [],
        terminalId: [],
        terminalName: [],
        businessAddress: '',
        location: '',
        labelId: ['2', '4', '5']
      },
      deleteForm: {
        placeId: '', // 商家ID
        placeName: '' // 商家名称
      },
      addRules: {
        airportList: [
          { required: true, message: '请选择机场', trigger: 'change' }
        ],
        address: [
          { max: 30, message: '商家地址最多30个字符', trigger: 'blur' }
        ],
        placeName: [
          { required: true, message: '请输入商场名称', trigger: 'blur' },
          { max: 20, message: '最多20个字符', trigger: 'blur' }
        ]
      },
      editRules: {
        airportList: [
          { required: true, message: '请选择机场', trigger: 'change' }
        ],
        placeName: [
          { required: true, message: '请输入商场名称', trigger: 'blur' },
          { max: 20, message: '最多20个字符', trigger: 'blur' }
        ],
        address: [
          { max: 30, message: '商家地址最多30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    setAddPoint () {
      return this.addForm.floor + 'F (' + this.addForm.longitude + ',' + this.addForm.latitude + ')'
      /**
       * self.addForm.latitude = self.svgSelect.center[0]
          self.addForm.longitude = self.svgSelect.center[1]
          self.editForm.latitude = self.svgSelect.center[0]
          self.editForm.longitude = self.svgSelect.center[1]
       */
    }
  },
  methods: {
    /** ************************************* 前端显示选择地图等 *************************************** */
    getCenterFun (pointList) {
      function Point (x, y) {
        this.x = x
        this.y = y
      }
      // Contour object
      function Contour (a) {
        this.pts = [] // an array of Point objects defining the contour
      }
      Contour.prototype.area = function () {
        var area = 0
        var pts = this.pts
        var nPts = pts.length
        var j = nPts - 1
        var p1
        var p2
        for (var i = 0; i < nPts; j = i++) {
          p1 = pts[i]
          p2 = pts[j]
          area += p1.x * p2.y
          area -= p1.y * p2.x
        }
        area /= 2
        return area
      }
      Contour.prototype.centroid = function () {
        var pts = this.pts
        var nPts = pts.length
        var x = 0
        var y = 0
        var f
        var j = nPts - 1
        var p1
        var p2
        for (var i = 0; i < nPts; j = i++) {
          p1 = pts[i]
          p2 = pts[j]
          f = p1.x * p2.y - p2.x * p1.y
          x += (p1.x + p2.x) * f
          y += (p1.y + p2.y) * f
        }
        f = this.area() * 6
        return new Point({x: x / f, y: y / f})
      }
      var polygon = pointList
      let con = new Contour()
      con.pts = polygon
      let c = con.centroid()
      c.x.x = c.x.x.toFixed(4)
      c.x.y = c.x.y.toFixed(4)
      return c.x
    },
    // 选择第一层，更换地图，样式等
    selectFloor (item, index, Form) {
      console.log('selectFloor')
      this[Form].floor = parseInt(index + 1)
      let svgStr = './static/shougang' + (index + 1) + '.svg' // svg地图路径
      // svgStr = './static/shougang1.svg' // svg地图路径
      this.$nextTick(function () {
        this.svgSelect.floorList.forEach((item) => {
          if (!item.active) {
            this.$set(item, 'active')
          }
          this.$set(item, 'active', false)
        })
        this.svgSelect.floorList[index].active = true
        this.loadSvgMap(svgStr, Form)
      })
    },
    // 初始化地图时设置每个地区的地标
    initAllStyle (Form, svgStr) {
      let floor = svgStr.split('shougang')[1].split('.')[0]
      let self = this
      d3.selectAll('.businessSelect').remove()
      d3.selectAll('.haveselect').remove()
      this.filterFormFro.allBusinessList = []

      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllBusiness(para).then(res => {
        if (res.data.body.result === 1000) {
          for (let i = 0; i < res.data.body.content.list.length; i++) {
            if (res.data.body.content.list[i].floor === parseInt(floor)) {
              this.filterFormFro.allBusinessList.push(res.data.body.content.list[i])
            }
          }
          let businessList = this.filterFormFro.allBusinessList
          // 切换地图时如果有已选择的坐标，则切换到对应层时append对应图标
          let pointAddress = self[Form].pointAddress
          for (let i = 0; i < businessList.length; i++) {
            if (this[Form].placeId !== businessList[i].placeId) {
              let location = d3.selectAll('#XMLID_1_')
              .append('g')
              .attr('transform', function (d) {
                // 计算标注点的位置
                return 'translate(' + businessList[i].longitude + ',' + businessList[i].latitude + ')'
              })
              location.append('svg:image')
                .attr('class', 'businessSelect')
                .attr('xlink:href', './static/img/icon-tuijianweidian-n3.png')
                .attr('width', 50)
                .attr('height', 50)
                .attr('x', -25)
                .attr('y', -45)
              // 画圆作为标注
            } else {
              console.log('777777777777777777')
              console.log(this[Form].placeId)
              console.log(businessList[i].placeId)
            }
          }
          if (pointAddress !== '') {
            let floor = parseInt(pointAddress.split('F')[0])
            let x = parseFloat(pointAddress.split(',')[0].split('(')[1])
            let y = parseFloat(pointAddress.split(',')[1].split(')')[0])
            if (parseInt(this[Form].floor) === floor) {
              let location = d3.selectAll('#XMLID_1_')
              .append('g')
              .attr('transform', function (d) {
                // 计算标注点的位置
                return 'translate(' + x + ',' + y + ')'
              })
              // 标注
              location.append('svg:image')
              .attr('class', 'haveselect')
              .attr('xlink:href', './static/img/icon.png')
              .attr('width', 60)
              .attr('height', 60)
              .attr('x', -30)
              .attr('y', -50)
            }
          }
          // 初始化左下角楼层选择样式
          let floorNum = parseInt(self[Form].floor) - 1
          if (!self.svgSelect.floorList[floorNum].active) {
            self.$set(self.svgSelect.floorList[floorNum], 'active', true)
          }
          // this.filterFormFro.allBusinessList = res.data.body.content.list
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
        this.pointVisible = true
        setTimeout(() => { this.pointVisible = false }, 1000)
        this.Note = '获取数据失败'
      })
    },
    // 加载svg地图文件
    loadSvgMap (svgStr, Form) {
      let self = this
      let svgDiv = d3.select(this.$el).selectAll('#svgmap')
      let promise = new Promise(function (resolve, reject) { // 地图加载完之后在执行
        // 载入svg文件
        d3.xml(svgStr,
          function (xml) {
            // 获取xml文件内容，并转化为string字符串
            let strinit = xml.documentElement
            let str = ''
            if (strinit.outerHTML) {
              str = strinit.outerHTML
            } else {
              var div = document.createElement('div')
              div.appendChild(strinit)
              str = div.innerHTML
            }
            // 在div中插入svg地图
            svgDiv.html(str)
            // 选取svg对象
            let svg = svgDiv.selectAll('svg')
            let storage = window.localStorage
            storage.originViewBox = svg.attr('viewBox')
            svg.attr('width', 500)
               .attr('height', 500)
            self.initAllStyle(Form, svgStr) // 初始化地图，设置每个地区的地标，各个样式等
            resolve()
          })
      })
      // 地图加载完成
      promise.then(function () {
        self.bindDrag(Form)
      })
      // promise.then(this.bindDrag)
      promise.then(function () {
        self.bindClick(Form)
      })
    },
    // 绑定拖动事件drag
    bindDrag (Form) {
      let _svg = this.svg()
      if (Form === 'addForm') {
        _svg = this.svgAdd()
      } else if (Form === 'editForm') {
        _svg = this.svgEdit()
      }
      // 获得原始svg的viewBox属性
      let storage = window.localStorage
      let originViewBox = storage.originViewBox.split(' ')
      /**
         * 修改viewBox完成平移缩放
         * **/
      let drag = d3.drag()
        .on('start', function (d) {
        })
        .on('end', function (d) {
        })
        .on('drag', function (d) {
          d3.select(this) // 移动效果就是改变viewBox（0,0,1000,1000）的前两个值
            .attr('viewBox', function (d) {
              let viewBox = _svg.attr('viewBox').split(' ') // 拆分viewBox的值为数组
              let ratio = 500 / viewBox[2]
              let flagx = 1 // 图片水平方向是否能够拖动，1为能
              let flagy = 1 // 图片竖直方向是否能够拖动，0为不能
              // 以下为判断图片水平和竖直方向能否拖动
              if (parseInt(viewBox[0]) + parseInt(viewBox[2]) <= parseInt(viewBox[2]) && (d3.event.dx >= 0)) {
                flagx = 0
                viewBox[0] = 0
              }
              if ((parseInt(viewBox[0]) + parseInt(viewBox[2]) >= parseInt(originViewBox[2])) && (d3.event.dx < 0)) {
                flagx = 0
                viewBox[0] = parseInt(originViewBox[2]) - parseInt(viewBox[2])
              }
              if (parseInt(viewBox[2]) === parseInt(originViewBox[2])) {
                flagx = 0
                viewBox[0] = 0
              }
              if (parseInt(viewBox[1]) + parseInt(viewBox[3]) <= parseInt(viewBox[3])) {
                if (parseInt(viewBox[1]) + parseInt(viewBox[3]) <= parseInt(viewBox[3]) && d3.event.dy <= 0) {
                  flagy = 1
                } else {
                  flagy = 0
                  viewBox[1] = 0
                }
              }
              if (parseInt(viewBox[1]) + parseInt(viewBox[3]) >= parseInt(originViewBox[3])) {
                if (d3.event.dy >= 0 && parseInt(viewBox[1]) + parseInt(viewBox[3]) >= parseInt(originViewBox[3])) {
                  flagy = 1
                } else {
                  flagy = 0
                  viewBox[1] = parseInt(originViewBox[3]) - parseInt(viewBox[3])
                }
              }
              if (parseInt(viewBox[3]) === parseInt(originViewBox[3])) {
                flagy = 0
              }
              if (flagx) {
                viewBox[0] = parseInt(viewBox[0]) - d3.event.dx / ratio
              } else {
              }
              if (flagy) {
                viewBox[1] = parseInt(viewBox[1]) - d3.event.dy / ratio
              } else {
              }
              let viewBoxStr = `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}` // 拼接为viewBox字符串
              return viewBoxStr
            })
        })
      _svg.call(drag)
    },
    // 绑定点击事件
    bindClick (Form) {
      let self = this
      // 选择所有的多边形polygon
      let polygon = this.svg().selectAll('polygon')
      let rect = this.svg().selectAll('rect')
      let pointVisible = ''
      Form === 'addForm' ? pointVisible = 'addpointVisible' : pointVisible = 'editpointVisible'
      // 绑定鼠标按下矩形时事件
      rect.on('mousedown', function () {
        // 获取具体的鼠标事件，0为左键，1为滚轮，2为右键
        let button = d3.event.button
        let selfD3 = d3.select(this)
        // let color = selfD3.attr('fill')
        if ((button === 2 && self.markClick === false) || (button === 0 && self.markClick === true)) {
          self.svgSelect[pointVisible] = true
          // 获得鼠标选取的矩形平均中心点
          self.svgSelect.center = self.getRectCenter(selfD3)
          self[Form].latitude = self.svgSelect.center.y
          self[Form].longitude = self.svgSelect.center.x
          self[Form].pointAddress = self[Form].floor + 'F (' + self[Form].longitude + ', ' + self[Form].latitude + ')'
          if (self.svgSelect.center.x) {
            d3.selectAll('.haveselect').remove()
            d3.selectAll('.editselect').remove()
            let location = d3.selectAll('#XMLID_1_')
            .append('g')
            .attr('transform', function (d) {
              // 计算标注点的位置
              return 'translate(' + parseFloat(self.svgSelect.center.x) + ',' + parseFloat(self.svgSelect.center.y) + ')'
            })
            location.append('svg:image')
              .attr('class', 'haveselect')
              .attr('xlink:href', './static/img/icon.png')
              .attr('width', 50)
              .attr('height', 50)
              .attr('x', -25)
              .attr('y', -45)
              // .attr('y', -40)
          }
          self.svgSelect.center = []
        } else if (button === 2 && self.markClick === true) {
          self.svgSelect[pointVisible] = true
          self.markClick = false
        }
      })
      // 绑定鼠标按下多边形事件
      polygon.on('mousedown', function () {
        // 获取具体的鼠标事件，0为左键，1为滚轮，2为右键
        let button = d3.event.button
        let selfD3 = d3.select(this)
        // let color = selfD3.attr('fill')
        if ((button === 2 && self.markClick === false) || (button === 0 && self.markClick === true)) {
          self.svgSelect[pointVisible] = true
          if (self.markClick === true) {
            // 取消标记
            // self.markClick = false
          }
          // 获得鼠标选取的多边形平均中心点
          self.svgSelect.center = self.getPolygonCenter(selfD3.attr('points').split(' '))
          self[Form].latitude = self.svgSelect.center.y
          self[Form].longitude = self.svgSelect.center.x
          self[Form].pointAddress = self[Form].floor + 'F (' + self[Form].longitude + ', ' + self[Form].latitude + ')'
          if (self.svgSelect.center.x) {
            d3.selectAll('.haveselect').remove()
            d3.selectAll('.editselect').remove()
            let location = d3.selectAll('#XMLID_1_')
            .append('g')
            .attr('transform', function (d) {
              // 计算标注点的位置
              return 'translate(' + parseFloat(self.svgSelect.center.x) + ',' + parseFloat(self.svgSelect.center.y) + ')'
            })
            location.append('svg:image')
              .attr('class', 'haveselect')
              .attr('xlink:href', './static/img/icon.png')
              .attr('width', 60)
              .attr('height', 60)
              .attr('x', -30)
              .attr('y', -45)
          }
        } else if (button === 2 && self.markClick === true) {
          self.svgSelect[pointVisible] = true
          self.markClick = false
        }
      })
      // 整个svg绑定一个右击事件，取消标记的选择状态
      this.svg().on('mousedown', function () {
        let button = d3.event.button
        if (self.markClick === true) {
          if (button === 2) {
            self.markClick = false
          }
        }
      })
    },
    // 获取所选rect中心
    getRectCenter (selfD3) {
      let finalList = [] // 最终中心点
      let initx = parseFloat(selfD3.attr('x')) + parseFloat(selfD3.attr('width')) / 2
      let inity = parseFloat(selfD3.attr('y')) + parseFloat(selfD3.attr('height')) / 2
      if (selfD3.attr('transform')) {
        let pointsAttr = selfD3.attr('transform').split('matrix')[1].split('(')[1].split(')')[0].split(' ')
        let pointsAttrList = [] // 对矩形transform属性进行处理得到的数组
        for (let i = 0; i < pointsAttr.length; i++) {
          if (pointsAttr[i] !== '') {
            pointsAttrList.push(pointsAttr[i])
          }
        }
        // a,b,c,d,e,f为rect中的transform(matrix)属性
        let a = parseFloat(pointsAttrList[0])
        let b = parseFloat(pointsAttrList[1])
        let c = parseFloat(pointsAttrList[2])
        let d = parseFloat(pointsAttrList[3])
        let e = parseFloat(pointsAttrList[4])
        let f = parseFloat(pointsAttrList[5])
        finalList.push({
          'x': (a * initx + inity * c + e).toFixed(4),
          'y': (b * initx + inity * d + f).toFixed(4)
        })
      } else {
        finalList.push({
          'x': initx.toFixed(4),
          'y': inity.toFixed(4)
        })
      }
      return finalList[0]
    },
    // 获得所选polygon中心
    getPolygonCenter (pointsAttr) {
      let pointsAttrList = [] // 对多边形points属性进行处理得到的数组
      for (let i = 0; i < pointsAttr.length; i++) {
        if (pointsAttr[i] !== '') {
          pointsAttrList.push(pointsAttr[i])
        }
      }
      let totalList = []
      let totalCenter = ''
      for (let i = 0; i < pointsAttrList.length; i++) {
        totalList.push({
          'x': parseFloat(pointsAttrList[i].split(',')[0]),
          'y': parseFloat(pointsAttrList[i].split(',')[1])
        })
      }
      /* var polygon = [
        {'x': 770.3423, 'y': 400.5555},
        {'x': 529.3434, 'y': 643.2353},
        {'x': 320.3455, 'y': 494.8865},
        {'x': 424.3477, 'y': 381.5678},
        {'x': 459.3488, 'y': 369.2332}
      ] */
      totalCenter = this.getCenterFun(totalList)
      return totalCenter
    },
    // 改变viewBox的大小，形成地图缩放的效果
    // i<0，扩大viewBox，视觉效果位地图缩小
    changeViewBoxSize (i) {
      // 获取原始viewBox
      let storage = window.localStorage
      let originViewBox = storage.originViewBox.split(' ')
      let viewMax = parseInt(originViewBox[2]) // viewBox最大值
      let viewMin = parseInt(originViewBox[2]) - 100 * 5 // viewBox最小值
      let viewBox = this.viewBox()
      if (i < 0) {
        // 注：viewBox[2]越大，则显得地图越小，所以点击缩小即为增加viewBox[2]和[3]
        // 如果viewBox大小的值大于最大值，直接赋值最大值
        viewBox[2] >= viewMax ? viewBox[2] = viewBox[3] = viewMax : viewBox[2] = viewBox[3] = viewBox[2] + 100
      } else {
        viewBox[2] <= viewMin ? viewBox[2] = viewBox[3] = viewMin : viewBox[2] = viewBox[3] = viewBox[2] - 100
      }
      // 设置viewBox属性
      let viewBoxStr = `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`
      this.svg().attr('viewBox', viewBoxStr)
    },
    // 标记选择状态
    markClickButton () {
      this.markClick = true
    },
    // 获取鼠标当前的坐标
    getXY (event) {
      // this.clientX = event.clientX
      // this.clientY = event.clientY
      this.clientX = event.clientX
      this.clientY = event.clientY
    },
    /** ************************************* 前端处理数据格式，显示等 *************************************** */
    // 点击上方标签“商家管理”
    setBusVisible () {
      this.editBusVisible = false
      this.addBusVisible = false
      this.BusVisible = true
      this.editBusLabelVisible = false
      this.busLabel = true
      this.addBaseSrc = './static/img/business-yes.png'
      this.addLabelSrc = './static/img/label-no.png'
      this.clearAddForm()
    },
    // 点击增加商家的“基本信息”和“标签选择”
    setBusLabelVisible (type) {
      if (type === 1) {
        this.addBusLabelVisible = false
        this.busLabel = true
        this.addBaseSrc = './static/img/business-yes.png'
        this.addLabelSrc = './static/img/label-no.png'
      } else {
        this.addBusLabelVisible = true
        this.busLabel = false
        this.addBaseSrc = './static/img/business-no.png'
        this.addLabelSrc = './static/img/label-yes.png'
      }
    },
    // 点击增加/编辑商家的“基本信息”和“标签选择”
    setEditBusLabelVisible (type) {
      if (type === 1) {
        this.editBusLabelVisible = false
        this.busLabel = true
        this.addBaseSrc = './static/img/business-yes.png'
        this.addLabelSrc = './static/img/label-no.png'
      } else {
        this.editBusLabelVisible = true
        this.busLabel = false
        this.addBaseSrc = './static/img/business-no.png'
        this.addLabelSrc = './static/img/label-yes.png'
      }
    },
    // 隐藏增加/编辑商家时上传图片按钮
    setaddImgVisible () {
      this.addImgVisible = false
    },
    // 隐藏增加/编辑商家时上传图片按钮
    seteditImgVisible () {
      this.editImgVisible = false
    },
    // 点击关闭增加商家，取消地图所选商家，
    closeAddPoint () {
      this.addForm.pointAddress = ''
      this.svgSelect.addpointVisible = false
      d3.selectAll('.haveselect').remove()
    },
    // 点击关闭编辑商家，取消地图所选商家，
    closeEditPoint () {
      this.editForm.pointAddress = ''
      this.svgSelect.editpointVisible = false
      d3.selectAll('.haveselect').remove()
    },
    // 点击关闭增加商家弹窗时重置addForm数据
    clearAddForm () {
      this.$nextTick(function () {
        this.$refs['addForm'].resetFields()
        this.$refs['editForm'].resetFields()
        this.svgSelect.floorList.forEach((item) => {
          if (!item.active) {
            this.$set(item, 'active')
          }
          this.$set(item, 'active', false)
        })
      })
      // 清空所选图片列表
      this.fileList = []
      // this.$refs['uploadImg'].uploadFiles = []
      this.$refs['uploadImg'].clearFiles()
      this.setLabelDropDown(this.addForm.allLabelList, 'addForm')
      this.addForm.labelIds = []
      this.svgSelect.addpointVisible = false
      this.addForm.floor = 1
      // this.addForm.floor = 3
      this.addForm.address = ''
      this.addImgVisible = true
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
        if (formName === 'addForm') {
          this.$refs['uploadImg'].clearFiles()
        }
      })
    },
    // 点击弹窗“关闭”提交数据增加商家
    submitAddBus () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.selectLabel('addForm') // 选择标签后再次保存
          let file = this.$refs['uploadImg'].uploadFiles[0]
          if (this.addForm.pointAddress === '') {
            this.$message.warning('请在基本资料中选择商家坐标')
            return false
          }
          if (this.addForm.labelIds.length === 0) {
            this.$message.warning('请在标签设置中选择商家标签')
            return false
          }
          if (file) {
            this.$refs.uploadImg.submit()
          } else {
            this.addBusinessFro()
          }
        }
      })
    },
    // 点击“保存”提交数据编辑商家
    submitEditBus () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.selectLabel('editForm') // 选择标签后再次保存
          if (this.editForm.pointAddress === '') {
            this.$message.warning('请在基本资料中选择商家坐标')
            return false
          }
          if (this.editForm.labelIds.length === 0) {
            this.$message.warning('请选择商家标签')
            return false
          }
          if (this.$refs['uploadEditImg'].uploadFiles[0]) {
            if (this.$refs['uploadEditImg'].uploadFiles[0].raw) {
              this.editForm.businessImgSrc = this.$refs['uploadEditImg'].uploadFiles[0].raw.url
              this.$refs.uploadEditImg.submit()
            } else {
              this.editBusinessFro()
            }
          } else {
            this.editBusinessFro()
          }
        } else {
          return false
        }
      })
    },
    // 修改或增加商家时点击“保存”后修改标签
    selectLabel (Form) {
      this[Form].labelIds = [] // 标签ID<>
      for (let i = 0; i < this[Form].categoryLabelList.length; i++) {
        for (let m = 0; m < this[Form].categoryLabelList[i].label.length; m++) {
          if (this[Form].categoryLabelList[i].label[m].type === 'primary') {
            this[Form].labelIds.push(parseInt(this[Form].categoryLabelList[i].label[m].labelId))
          }
        }
      }
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterForm.currentPage = val
      this.getBusinessListFro()
    },
    // 下拉框选择机场及航站楼
    selectAirport (Form) {
      console.log('下拉框发生变化')
      for (let i = 0; i < this[Form].airportNameList.length; i++) {
        this[Form].terminalId = []
        if (this[Form].airportNameList[i].label === this[Form].airportList[0]) {
          this[Form].airportId = this[Form].airportNameList[i].airportId
          this[Form].airportName = this[Form].airportNameList[i].label
          for (let m = 0; m < this[Form].airportNameList[i].terminals.length; m++) {
            if (this[Form].airportList[1] === this[Form].airportNameList[i].terminals[m].label && this[Form].airportList[1] !== '全部') {
              this[Form].terminalId.push(this[Form].airportNameList[i].terminals[m].terminalId)
              this[Form].terminalName.push(this[Form].airportNameList[i].terminals[m].label)
              break
            } else if (this[Form].airportList[1] === '全部') {
              if (this[Form].airportNameList[i].terminals[m].label !== '全部') {
                this[Form].terminalId.push(this[Form].airportNameList[i].terminals[m].terminalId)
                this[Form].terminalName.push(this[Form].airportNameList[i].terminals[m].label)
              }
            }
          }
          break
        }
      }
      if (Form === 'addForm' || Form === 'editForm') {
        this[Form].placeName = ''
        this[Form].address = ''
        this.fileList = [] // 清空所选图片列表
        this[Form].address = ''
        this[Form].floor = 1
        this[Form].labelIds = []
        this.setLabelDropDown(this[Form].allLabelList, Form)
        d3.selectAll('.haveselect').remove()
        if (Form === 'addForm') {
          this.$refs['uploadImg'].clearFiles()
          this.svgSelect.addpointVisible = false
          this.addImgVisible = true
        } else if (Form === 'editForm') {
          this.$refs['uploadEditImg'].clearFiles()
          this.svgSelect.editpointVisible = false
          this.editImgVisible = true
        }
      }
    },
    // 选完筛选条件后点击“查询”
    submitSearch () {
      this.filterForm.currentPage = 1
      this.getBusinessListFro()
    },
    // 点击增加商家按钮
    addBusinessVisible () {
      this.addBusVisible = true
      this.BusVisible = false
      this.editBusVisible = false
      this.addBusLabelVisible = false
      // this.addVisible = true
      // 元素加载完成后加载地图
      this.$nextTick(() => {
        let svgStr = './static/shougang1.svg'
        // let svgStr = '../../../static/shougang1.svg'
        this.loadSvgMap(svgStr, 'addForm')
        this.addForm.pointAddress = '' // 点击增加商家初始化地图上方选择图标位置，毕竟编辑中的覆盖
      })
    },
    // 增加商家“删除”暂存列表图片
    addhandleRemove (file, fileList) {
      this.addImgVisible = true
    },
    // 编辑商家“删除”暂存列表图片
    edithandleRemove (file, fileList) {
      this.editImgVisible = true
    },
    // 编辑商家信息中上传图片组件状态改变
    edithandleChange (file, fileList) {
      this.editImgVisible = false
    },
    // 增加商家信息中上传图片组件状态改变
    addhandleChange (file, fileList) {
      this.addImgVisible = false
    },
    handlePreview (file) {
    },
    // 批量上传个数限制
    handleExceed (files, fileList) {
      this.$message.warning(`一次只能上传一个文件，本次选择了 ${files.length} 个文件`)
    },
    // excel文件上传前进行检验格式
    beforeUploadExc (file) {
      const isExcel = file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.warning('批量导入文件类型应为.xls')
      }
      return isExcel
    },
    // 图片上传前进行检验大小格式
    beforeUploadImg (file) {
      const imgSize = file.size / 1024 < 50
      const isPicture = (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/tiff')
      if (!isPicture) {
        this.$message.error('请选择图片进行上传')
      }
      if (!imgSize) {
        this.$message.error('上传头像图片大小不能超过 50K!')
      }
      return imgSize && isPicture
    },
    // 文件上传时
    onProgress (event, file, fileList) {
      this.loading2 = true
      this.pointVisible = true
      this.Note = '文件正在上传'
    },
    // 文件上传失败
    onError (err, file, fileList) {
      let fs = document.getElementsByName('file')
      if (fs.length > 0) {
        fs.value = null
      }
      this.loading2 = false
      this.pointVisible = false
      this.Note = ''
      localStorage.error = err
      this.$message.error('文件上传失败99')
    },
    // 文件上传失败
    onErrorFile (err, file, fileList) {
      let fs = document.getElementsByName('file')
      if (fs.length > 0) {
        fs.value = null
      }
      this.loading2 = false
      this.pointVisible = false
      this.Note = ''
      localStorage.error = err
      this.$message.error('文件上传失败')
    },
    // 文件上传成功
    onSuccessFile (response, file, fileList) {
      let fs = document.getElementsByName('file')
      if (fs.length > 0) {
        fs.value = null
      }
      this.loading2 = false
      this.pointVisible = false
      this.Note = ''
      this.$message.success('文件上传成功')
    },
    // 文件上传成功
    onSuccess (response, file, fileList) {
      let fs = document.getElementsByName('file')
      if (fs.length > 0) {
        fs.value = null
      }
      this.loading2 = false
      this.pointVisible = false
      this.Note = ''
      this.$message.success('文件上传成功')
    },
    // 设置表头
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    // 设置表行
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 表格中点击“编辑”按钮
    handleEdit (index, row) {
      this.editForm.businessImgSrc = ''
      this.svgSelect.editpointVisible = true
      this.editForm.isImage = 0
      let data = this.filterFormFro.tableData[index]
      this.editForm.index = index
      this.editForm.airportList = []
      this.editForm.airportList[0] = data.figureThree + ' ' + data.airportName
      this.editForm.airportList[1] = data.terminalName
      this.editForm.airportName = data.airportName
      this.editForm.airportId = data.airportId
      this.editForm.terminalName[0] = data.terminalName
      this.editForm.terminalId[0] = data.terminalId
      this.editForm.placeName = data.placeName
      this.editForm.placeId = data.placeId
      this.editForm.address = data.address
      this.getBusLabelFro() // 从后台获取该商家的标签
      this.editForm.latitude = parseFloat(this.filterFormFro.tableData[index].latitude)
      this.editForm.longitude = parseFloat(this.filterFormFro.tableData[index].longitude)
      this.editForm.floor = parseInt(this.filterFormFro.tableData[index].floor)
      // 只有一张地图测试用楼层
      // this.editForm.floor = 3
      this.editForm.pointAddress = this.editForm.floor + 'F (' + this.editForm.longitude + ', ' + this.editForm.latitude + ')' // 初始化
      this.editForm.businessImgSrc = data.imgSrc
      // this.editForm.businessImgSrc = 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      if (this.editForm.businessImgSrc) {
        this.editForm.isImage = 1
        this.editImgVisible = false
        this.editForm.fileListEdit = [{
          status: 'success',
          uid: '',
          url: this.editForm.businessImgSrc
        }]
      } else {
        this.editForm.fileListEdit = []
        this.editForm.isImage = 0
        this.editImgVisible = true
      }
      if (this.editForm.file) {
        this.editForm.file = null
      }
      this.uploadEditImgShow = false
      this.addBusVisible = false
      this.BusVisible = false
      this.editBusVisible = true
      this.editBusLabelVisible = false
      this.$nextTick(() => {
        let svgStr = './static/shougang' + this.editForm.floor + '.svg'
        // let svgStr = './static/shougang1.svg'
        // let svgStr = '../../../static/shougang1.svg'
        this.loadSvgMap(svgStr, 'editForm')
        this.uploadEditImgShow = true
      })
      // this.editVisible = true
    },
    // 表格中点击“删除”按钮
    handleDelete (index, row) {
      this.deleteForm.placeId = parseInt(this.filterFormFro.tableData[index].placeId)
      this.$confirm('确定删除该商家吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteBusinessListFro()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 选择商家标签，并改变样式
    changeLabel (i, index, item, Form) {
      this.$nextTick(function () {
        this[Form].categoryLabelList[i].label[index].type === 'primary' ? this[Form].categoryLabelList[i].label[index].type = 'info' : this[Form].categoryLabelList[i].label[index].type = 'primary'
        this[Form].categoryLabelList[i].label[index].icon === 'el-icon-check' ? this[Form].categoryLabelList[i].label[index].icon = '' : this[Form].categoryLabelList[i].label[index].icon = 'el-icon-check'
      })
    },
    // 处理后台发来的数据以显示在下拉框中（主要针对机场和航站楼，使其可以二级联动选择）
    setDropdown (testAirport, form) {
      let parentIdList = []
      let totalList = []
      for (let i = 0; i < testAirport.length; i++) {
        if (parentIdList.indexOf(testAirport[i].airportId) === -1) {
          parentIdList.push(testAirport[i].airportId)
          totalList.push({
            label: testAirport[i].figureThree + ' ' + testAirport[i].airportName,
            airportId: testAirport[i].airportId,
            terminals: []
          })
        }
      }
      for (let i = 0; i < totalList.length; i++) {
        testAirport.forEach((item) => {
          if (item.airportId === totalList[i].airportId) {
            totalList[i].terminals.push({
              label: item.terminalName,
              terminalId: item.terminalId
            })
          }
        })
      }
      if (form === 'filterForm') {
        for (let i = 0; i < totalList.length; i++) {
          totalList[i].terminals.push({
            label: '全部',
            terminalId: ''
          })
        }
      }
      this[form].airportNameList = totalList
    },
    /** ************************************* 提交后台相关函数 *************************************** */
    // 向后台查询所有机场航站楼
    getAllTerminalFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'airportService_v1'
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllTerminal(para).then(res => {
        let terminalList = []
        if (res.data.body.result === 1000) {
          terminalList = res.data.body.content.list
          this.setDropdown(terminalList, 'filterForm')
          this.setDropdown(terminalList, 'addForm')
          this.setDropdown(terminalList, 'editForm')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台发送信息批量导入商家信息(excel)
    uploadBusinessFro () {
      this.loading = true
      let file = this.$refs['uploadExc'].uploadFiles[0].raw
      let para = new FormData()
      para.append('header', JSON.stringify({
        'token': sessionStorage.getItem('token')
      }))
      para.append('body', JSON.stringify({}))
      para.append('fileName', file)
      // apiFile.getAllCustomerShou(para).then(res => {
      apiFile.addImportBusiness(para).then(res => {
        this.$refs['uploadExc'].clearFiles()
        this.loading = false
        if (res.data.body.result === 1000) {
          if (res.data.body.content.length > 0) {
            let erorMessage = ''
            for (let i = 0; i < res.data.body.content.length; i++) {
              erorMessage = erorMessage + '<span>表格第' + res.data.body.content[i].id + '行 ' + res.data.body.content[i].message + '</span></br>'
            }
            console.log(erorMessage)
            this.$message({
              dangerouslyUseHTMLString: true,
              message: erorMessage,
              type: 'error'
            })
            // this.$message.error(erorMessage)
          } else {
            this.filterForm.currentPage = 1
            this.getBusinessListFro()
            this.$message.success('导入成功，请将相关资料完善')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$refs['uploadExc'].clearFiles()
        this.loading = false
        this.$message.error(error)
      })
    },
    // 向后台和图片一起提交添加商家表单
    addBusinessFro () {
      let file = this.$refs['uploadImg'].uploadFiles[0]
      // let fileValue = document.querySelector('.el-upload-img .el-upload__input')
      let para = new FormData()
      if (file) { // 如果有图片
        para.append('imge', file.raw)
      }
      // this.addForm.labelIds = [1, 2, 3]
      para.append('header', JSON.stringify({
        'token': sessionStorage.getItem('token'),
        'beanId': 'businessManageService_v1'
      }))
      para.append('body', JSON.stringify({
        // 'address': this.addForm.airportName + this.addForm.terminalName + this.addForm.floor + '楼',
        'address': this.addForm.address,
        'airportId': this.addForm.airportId,
        'placeName': this.addForm.placeName,
        'latitude': this.addForm.latitude,
        'longitude': this.addForm.longitude,
        'floor': this.addForm.floor,
        'labelIds': this.addForm.labelIds,
        'terminalId': this.addForm.terminalId[0]
      }))
      this.addForm.file = file
      // apiBus.addBusiness(para).then(res => {
      apiFile.addBusiness(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('商家信息提交成功')
          this.filterForm.currentPage = 1
          this.getBusinessListFro()
          this.clearAddForm()
          this.editBusVisible = false
          this.addBusVisible = false
          this.BusVisible = true
          this.editBusLabelVisible = false
          this.busLabel = true
          this.addBaseSrc = './static/img/business-yes.png'
          this.addLabelSrc = './static/img/label-no.png'
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台和图片一起提交编辑商家表单
    editBusinessFro () {
      let isDelete = 0
      let file = this.$refs['uploadEditImg'].uploadFiles
      let para = new FormData()
      if (this.editForm.isImage === 0) {
        isDelete = 0
        if (file[0]) {
          if (file[0].raw) {
            para.append('imge', file[0].raw)
          }
        }
      } else {
        if (file[0]) {
          if (file[0].raw) {
            para.append('imge', file[0].raw)
          } else {
            isDelete = 0
          }
        } else {
          isDelete = 1
        }
      }
      para.append('header', JSON.stringify({
        token: sessionStorage.getItem('token'),
        beanId: 'businessManageService_v1'
      }))
      para.append('body', JSON.stringify({
        'placeId': parseInt(this.editForm.placeId),
        'businessName': this.editForm.placeName,
        'airportId': this.editForm.airportId,
        'latitude': parseFloat(this.editForm.latitude),
        'longitude': parseFloat(this.editForm.longitude),
        'address': this.editForm.address,
        // 'address': this.editForm.airportName + this.editForm.terminalName + this.editForm.floor + '楼',
        'floor': this.editForm.floor,
        'labelIds': this.editForm.labelIds,
        'terminalId': parseInt(this.editForm.terminalId[0]),
        'isDelete': isDelete
      }))
      apiFile.editBusiness(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          this.$message.success('编辑商家信息成功')
          this.filterForm.currentPage = 1
          this.getBusinessListFro()
          this.editBusVisible = false
          this.addBusVisible = false
          this.BusVisible = true
          this.editBusLabelVisible = false
          this.busLabel = true
          this.addBaseSrc = './static/img/business-yes.png'
          this.addLabelSrc = './static/img/label-no.png'
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 从后台获取筛选商家列表
    getBusinessListFro () {
      this.loading = true
      this.paginationVisible = false
      let terminalId = ''
      this.filterForm.terminalId.length > 1 ? terminalId = '' : terminalId = parseInt(this.filterForm.terminalId[0])
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          pageNum: parseInt(this.filterForm.currentPage),
          airportId: parseInt(this.filterForm.airportId),
          terminalId: terminalId,
          placeName: this.filterForm.placeName
        })
      }
      this.filterFormFro.tableData = this.testData
      // setTimeout(() => { this.pointVisible = false }, 1000)
      apiBus.getBusinessList(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          let resData = res.data.body.content
          if (resData.list.length > 0) {
            this.filterFormFro.tableData = resData.list
            for (let i = 0; i < resData.list.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterForm.currentPage) - 1) * 15 + (i + 1)
              this.filterFormFro.tableData[i].businessAddress = resData.list[i].address
              this.filterFormFro.tableData[i].location = 'F' + resData.list[i].floor + ' (' + resData.list[i].longitude + ',' + resData.list[i].latitude + ')'
            }
            this.filterFormFro.totalPage = resData.allPage
            this.filterFormFro.totalPage < 2 ? this.paginationVisible = false : this.paginationVisible = true
            this.$message.success('成功获得商家列表')
          } else {
            this.paginationVisible = false
            this.$message.success('没有任何商家信息！')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 从后台删除商家
    deleteBusinessListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          placeId: parseInt(this.deleteForm.placeId)
        })
      }
      apiBus.deleteBusinessList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterForm.currentPage = 1
          this.getBusinessListFro() // 删除后重新获取数据
          this.$message.success('成功删除商家！')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 将从后台获得标签分类信息显示在弹窗中
    setLabelDropDown (dataNow, Form) {
      let categoryNow = [] // 包含的分类名称
      this[Form].categoryLabelList = []
      for (let i = 0; i < dataNow.length; i++) {
        if (categoryNow.indexOf(dataNow[i].className) === -1) {
          this[Form].categoryLabelList.push({
            category: dataNow[i].className,
            categoryId: dataNow[i].classId,
            label: []
          })
          categoryNow.push(dataNow[i].className)
        }
      }
      for (let i = 0; i < dataNow.length; i++) {
        this[Form].categoryLabelList[categoryNow.indexOf(dataNow[i].className)].label.push({
          value: dataNow[i].labelName,
          type: 'info',
          icon: '',
          labelId: dataNow[i].labelId
        })
      }
    },
    // 从后台获得添加电商处所有电商标签查询
    getAllBusLabelFro (Form) {
      let dataNow = [] // 从服务器获得的数据
      // let businessId = ''
      // Form === 'editForm' ? businessId = parseInt(this.editForm.businessId) : businessId = ''
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          // businessId: businessId
        })
      }
      apiBus.getAllBusLabel(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          if (res.data.body.content.list.length > 0) {
            // 处理数据以显示商家标签
            dataNow = res.data.body.content.list
            this.addForm.allLabelList = dataNow
            this.editForm.allLabelList = dataNow
            this.setLabelDropDown(dataNow, 'addForm')
            this.setLabelDropDown(dataNow, 'editForm')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
        this.loading = false
      })
    },
    // 从后台获得编辑电商处电商标签查询
    getBusLabelFro (Form) {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          placeId: parseInt(this.editForm.placeId)
          // businessId: businessId
        })
      }
      apiBus.getBusLabel(para).then(res => {
        if (res.data.body.result === 1000) {
          if (res.data.body.content.list.length > 0) {
            this.editForm.labelList = res.data.body.content.list
            // 处理数据以显示商家标签
            let labelIdList = []
            for (let i = 0; i < this.editForm.labelList.length; i++) {
              labelIdList.push(this.editForm.labelList[i].labelId)
            }
            for (let i = 0; i < this.editForm.categoryLabelList.length; i++) {
              for (let m = 0; m < this.editForm.categoryLabelList[i].label.length; m++) {
                if (labelIdList.indexOf(parseInt(this.editForm.categoryLabelList[i].label[m].labelId)) !== -1) {
                  this.editForm.categoryLabelList[i].label[m].type = 'primary'
                  this.editForm.categoryLabelList[i].label[m].icon = 'el-icon-check'
                } else {
                  this.editForm.categoryLabelList[i].label[m].type = 'info'
                  this.editForm.categoryLabelList[i].label[m].icon = ''
                }
              }
            }
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
        this.loading = false
      })
    }
  },
  watch: {
    // 监测标记按钮是否点击
    markClick: function (newMark, oldMark) {
      if (newMark === true) {
        // 如果点击，切换鼠标为画笔样式
        this.svgSelect.isCursor = true
        /* let span = d3.select(this.$el).append('span')
        span.text('鼠标左键点击，鼠标右键取消')
          .style('position', 'absolute')
          .style('left', this.clientX + 20 + 'px')
          .style('top', this.clientY + 'px')
          // 绑定鼠标移动事件
        document.onmousemove = function (e) {
          span.style('left', e.clientX + 20 + 'px')
          span.style('top', e.clientY + 'px')
        } */
      } else if (newMark === false) {
        // d3.select(this.$el).select('span').remove()
        this.svgSelect.isCursor = false
      }
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 239 - 20
    this.addBusWidth = (document.body.scrollWidth - 219) / 2 - (800 / 2) - 20
    this.addBusLabelWidth = (document.body.scrollWidth - 219) / 2 - (944 / 2) - 20
  }
}
</script>